package io.github.harmonly.controller.api;

import io.github.harmonly.entity.User;
import io.github.harmonly.entity.association.Member;
import io.github.harmonly.service.MemberService;
import io.github.harmonly.service.UserService;
import io.github.harmonly.util.JSONUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/api")
public class MemberController {

    @Resource
    private MemberService service;
    @Resource
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/member_by_uid/{uid}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getAssociations(@PathVariable("uid") int uid) {
        return JSONUtil.toJSONString(service.getAssociations(uid));
    }

    @ResponseBody
    @RequestMapping(value = "/member_by_aid/{aid}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getUsers(@PathVariable("aid") int aid) {
        return JSONUtil.toJSONString(service.getUsers(aid));
    }

    @ResponseBody
    @RequestMapping(value = "/member", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public String addMember(HttpSession session, @RequestBody String json) {
        boolean result = service.addMember(JSONUtil.parseObject(json, Member.class));
        User user = (User) session.getAttribute("user");
        session.setAttribute("user", userService.getUser(user.getUid()));
        return JSONUtil.result(result);
    }

    @ResponseBody
    @RequestMapping(value = "/member", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.DELETE)
    public String deleteMember(HttpSession session, @RequestBody String json) {
        boolean result = service.deleteMember(JSONUtil.parseObject(json, Member.class));
        User user = (User) session.getAttribute("user");
        session.setAttribute("user", userService.getUser(user.getUid()));
        return JSONUtil.result(result);
    }
}
